package com.rocksdata.mc.ui.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;

import com.ctz.commonframe.ui.BaseActivity;
import com.ctz.commonframe.ui.BaseFragment;
import com.ctz.commonframe.ui.WebViewActivity;
import com.ctz.commonframe.ui.view.ptr.PullToRefreshBase;
import com.ctz.commonframe.ui.view.ptr.PullToRefreshListView;
import com.ctz.commonframe.ui.widget.AbsAdapter;
import com.ctz.commonframe.ui.widget.AdapterViewHolder;
import com.rocksdata.mc.BuildConfig;
import com.rocksdata.mc.MobileCampusApplication;
import com.rocksdata.mc.business.BusinessInterface;
import com.rocksdata.mc.business.BusinessManager;
import com.rocksdata.mc.entity.AnnouncementInfo;
import com.rocksdata.mc.R;
import com.rocksdata.mc.business.UserInfoManager;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 陈堂正 on 2017/3/15.
 */
@ContentView(R.layout.fragment_announcement_child)
public class AnnouncementChildFragment extends BaseFragment implements TextWatcher {
    @ViewInject(R.id.lv_notification)
    private PullToRefreshListView lvNotification;

    private List<AnnouncementInfo> announcementInfoList = new ArrayList<>();
    private AnnouncementListAdapter adapter;
    private int index = 1;
    private String lastDate;
    private int announcementType;
    private BusinessInterface.IAnnouncementManager manager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        manager = BusinessManager.getAnnouncementManager();
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        Bundle data = getArguments();
        if (data == null) return;
        announcementType = data.getInt("notification_type");
        lvNotification.setMode(PullToRefreshBase.Mode.BOTH);
        adapter = new AnnouncementListAdapter(getActivity(), announcementInfoList);
        lvNotification.setAdapter(adapter);
        lvNotification.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                refresh();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                loadMore();
            }
        });
        lvNotification.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                AnnouncementInfo info = adapter.getItem(position - 1);
                try {
                    String url = "file:///android_asset/www/index.html"
                            + "#/announcement/" + info.getNoticeCode()
                            + "?baseUrl=" + URLEncoder.encode(BuildConfig.HOST, "UTF-8")
                            + "&token=" + UserInfoManager.getAccessToken()
                            + "&userType=" + UserInfoManager.getCurrentUserType()
                            + "&userId=" + UserInfoManager.getCurrentUserId()
                            + "&backClose";
                    Intent intent = new Intent(mContext, WebViewActivity.class);
                    intent.putExtra(WebViewActivity.EXTRA_KEY_URL, url);
                    startActivity(intent);
                    manager.setRead(info.getNoticeCode());
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        });
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    protected void onVisible() {
        refresh();
    }

    private void refresh(){
        index = 1;
        lastDate = null;
        announcementInfoList.clear();
        getNotificationList();
    }

    private void loadMore(){
        index++;
        int size = announcementInfoList.size();
        if(size > 0){
            lastDate = announcementInfoList.get(size - 1).getPublishedTime();
        }
        getNotificationList();
    }

    @SuppressWarnings("unchecked")
    private void getNotificationList() {
        if (UserInfoManager.isVisitor()) return;
        manager.getAnnouncementListRemote(index, announcementType, lastDate, new BusinessInterface.OnBusinessResultListener() {
            @Override
            public void onBusinessResult(boolean isSuccess, Object object, String message) {
                if (isSuccess) {
                    if (object != null) {
                        List<AnnouncementInfo> list = (List<AnnouncementInfo>) object;
                        for (AnnouncementInfo info: list) {
                            if(!announcementInfoList.contains(info)){
                                announcementInfoList.add(info);
                            }
                        }
                        adapter.notifyDataSetChanged();
                    }
                }else{
                    if(index > 1)
                        index--;
                }
                lvNotification.onRefreshComplete();
                ((BaseActivity)mContext).dismissLoadingDialog();
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        if (s.length() == 0) {
            adapter = new AnnouncementListAdapter(MobileCampusApplication.getContext(), announcementInfoList);
        } else {
            List<AnnouncementInfo> resultList = new ArrayList<>();
            for (AnnouncementInfo info : announcementInfoList) {
                if (info.getTitle().contains(s) || info.getContent().contains(s)) {
                    resultList.add(info);
                }
            }
            adapter = new AnnouncementListAdapter(MobileCampusApplication.getContext(), resultList);
        }
        if (adapter != null)
            lvNotification.setAdapter(adapter);
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

//    @Override
//    public void onSearchResult(CharSequence result) {
//        if(result.length() == 0){
//            adapter = new NotificationListAdapter(mContext, announcementInfoList);
//        }else {
//            List<AnnouncementInfo> resultList = new ArrayList<>();
//            for (AnnouncementInfo info : announcementInfoList) {
//                if (info.getTitle().contains(result) || info.getContent().contains(result)) {
//                    resultList.add(info);
//                }
//            }
//            adapter = new NotificationListAdapter(mContext, resultList);
//        }
//        lvNotification.setAdapter(adapter);
//    }

    private class AnnouncementListAdapter extends AbsAdapter<AnnouncementInfo> {

        private AnnouncementListAdapter(Context context, List<AnnouncementInfo> datas) {
            super(context, datas, R.layout.item_notification_list);
        }

        @Override
        public void convert(AdapterViewHolder holder, AnnouncementInfo data) {
            View readFlag = holder.getView(R.id.view_read_flag);
            TextView tvTitle = holder.getView(R.id.tv_notification_title);
            TextView tvContent = holder.getView(R.id.tv_notification_content);
            TextView tvDate = holder.getView(R.id.tv_notification_date);
            TextView tvCreator = holder.getView(R.id.tv_notification_creator);

            readFlag.setVisibility(data.isRead() ? View.INVISIBLE : View.VISIBLE);
//            readFlag.setVisibility(manager.isRead(data.getId()) ? View.INVISIBLE : View.VISIBLE);
            tvTitle.setText(data.getTitle());
            tvContent.setText(data.getContent());
            tvDate.setText(data.getPublishedTime());
            tvCreator.setText(data.getDepartmentName());
        }
    }
}
